#include "MApplication.h"
#include "GStreamer.h"
#include "VideoSettings.h"
#include "VideoManager.h"

#include <QNetworkProxyFactory>
#include <QQuickWindow>
#include <QRunnable>


class MPlayVideoInitialization : public QRunnable
{
public:
    MPlayVideoInitialization(VideoManager *mgr) { _mgr = mgr; };
    void run() { _mgr->startVideo(); }
private:
    VideoManager *_mgr = nullptr;
};

MApplication* MApplication::_app = nullptr;

MApplication* qgcApp(void)
{
    return MApplication::_app;
}

MApplication::MApplication(int &argc, char *argv[])
    : QApplication(argc, argv)
{
    _app = this;

    QNetworkProxyFactory::setUseSystemConfiguration(true);

    setApplicationName("MPlayer");

    qDebug() << "Application version:" << "MPlay 1.0.0";

    GStreamer::initialize(argc, argv);

    _videoManager = new VideoManager(this);

    _videoSettings = static_cast<VideoSettings*>(VideoSettings::GetInstance(NULL, NULL));
}

MApplication::~MApplication()
{
    _app = nullptr;
}

VideoSettings *MApplication::videoSettings()
{
    return _videoSettings;
}

bool MApplication::_initForNormalAppBoot()
{
    _qmlAppEngine = new QQmlApplicationEngine(this);
    _qmlAppEngine->addImportPath("qrc:/qml");
    _qmlAppEngine->addImportPath("qrc:/qml/MControls");
    _qmlAppEngine->load(QUrl("qrc:/qml/MainRootWindow.qml"));

    QQuickWindow *rootWindow = (QQuickWindow *)qgcApp()->mainRootWindow();
    if (rootWindow) {
        rootWindow->scheduleRenderJob(new MPlayVideoInitialization(_videoManager), QQuickWindow::BeforeSynchronizingStage);
    }

    return true;
}

void MApplication::_initCommon()
{
    // qmlRegisterType
    // qmlRegisterSingletonType
    // qmlRegisterUncreatableType

    qmlRegisterSingletonType<VideoSettings>("MPlayer.VideoSettings", 1, 0, "VideoSettings", &VideoSettings::GetInstance);
}

void MApplication::_shutdown()
{
    qDebug() << "MPlay app exit";
    _qmlAppEngine->deleteLater();
}

QQuickItem *MApplication::mainRootWindow()
{
    if (_mainRootWindow == nullptr) {
        _mainRootWindow = reinterpret_cast<QQuickItem*>(_rootQmlObject());
    }
    return _mainRootWindow;
}

QObject *MApplication::_rootQmlObject()
{
    if (_qmlAppEngine && _qmlAppEngine->rootObjects().size()) {
        return _qmlAppEngine->rootObjects().at(0);
    }
    return nullptr;
}
